/*
厨师和美食家
盘子里只能放下一个馒头，吃够10个，游戏结束
厨师做馒头，2000ms，wait  notify
美食家吃馒头，吃一个300ms，
 */

public class J2 {
    static int count = 0;
    static int sum = 2;
    static Object chushiLock = new Object();
    static Object meishijiaLock = new Object();
    public static void main(String[] args) {
        Thread chushi = new Thread(()->{
            while (true){
                if(count==0){
                    System.out.println("厨师发现没馒头了，开始做馒头，用时2s...");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    count=1;
                    System.out.println("厨师做好馒头了！");
                }else{
                    System.out.println("厨师发现有馒头了，通知美食家来吃");
                    synchronized (meishijiaLock){
                        meishijiaLock.notify();
                    }
                    System.out.println("厨师发现有馒头，休眠");
                    synchronized (chushiLock) {
                        try {
                            chushiLock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });

        Thread meishijia = new Thread(()->{
            while (true){
                if(sum==0)System.exit(0);
                if(count==0){
                    System.out.println("美食家发现没有馒头，通知厨师做馒头");
                    synchronized (chushiLock){
                        chushiLock.notify();
                    }
                    System.out.println("美食家发现没有馒头，休眠...");
                    synchronized (meishijiaLock){
                        try {
                            meishijiaLock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }else{
                    System.out.println("美食家发现有馒头，开吃，2秒...");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    count=0;
                    sum--;
                    System.out.println("美食家把馒头吃完了");
                }
            }
        });
        System.out.println("厨师登场。。。");
        chushi.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("美食家登场。。");
        meishijia.start();
    }
}
